﻿using System;
using System.Collections.ObjectModel;
using Microsoft.Practices.Prism;
using Microsoft.Practices.Prism.ViewModel;
using Okazuki.MVVM.PrismSupport.Utils;
using wpf_ImageSearch.Model.YahooApis;

namespace wpf_ImageSearch.Model
{
    public class Main : NotificationObject
    {
        public Main()
        {
            ObjectUtils.Init(this);
        }

        private YahooApiClient client =
            new YahooApiClient("ba08XLmxg66sOc2jmKpR7TQ7x_xANB8VtT9KzrNhCSQtbaXe_qUQ9zBSS5.Ax9Lfww--");

        private Settings settings = Settings.Load();
        public Settings Settings
        {
            get
            {
                return settings;
            }
        }

        [AutoInit]
        public ObservableCollection<ImageSearchResultItem> Items { private set; get; }

        private long availableCount;
        public long AvailableCount
        {
            protected set
            {
                availableCount = value;
                RaisePropertyChanged(() => AvailableCount);
            }
            get
            {
                return availableCount;
            }
        }

        private string lastQuery;
        public string LastQuery
        {
            protected set
            {
                lastQuery = value;
                RaisePropertyChanged(() => LastQuery);
            }
            get
            {
                return lastQuery;
            }
        }

        public long AddItems(ImageSearchResult items)
        {
            if (items.TotalResultsReturned != 0)
            {
                Items.AddRange(items);
                return items.TotalResultsAvailable;
            }
            else if (items.ErrorMessage != null)
            {
                throw new ApplicationException(items.ErrorMessage);
            }
            return 0L;
        }

        public void Search(string query)
        {
            Items.Clear();
            AvailableCount = 0;
            var result = client.ImageSearch(query);
            AvailableCount = AddItems(result);
            LastQuery = query;
        }

        public void GetNext()
        {
            var result = client.ImageSearch(LastQuery, start: Items.Count + 1);
            AvailableCount = AddItems(result);
        }
    }
}
